//egret example 1
precision lowp float;
varying vec2 vTextureCoord;
varying vec4 vColor;
uniform sampler2D uSampler;

uniform float iTime;

//必须放在使用其的 frag函数之前，否则无法识别。
//核心：计算函数，角度，uv,光带的x长度，间隔，开始时间，偏移，单次循环时间
float inFlash(float currentTime, float angle,vec2 uv,float xLength,float interval,float beginTime, float offX, float loopTime )
{
	//亮度值
	float brightness =0.0;

	//倾斜角
	float angleInRad = 0.0174444 * angle;

	//当前时间
	//float currentTime = _Time.y;

	//获取本次光照的起始时间
	float currentTimeInt = float(int(currentTime/interval)) * interval;
	//获取本次光照的流逝时间 = 当前时间 - 起始时间
	float currentTimePassed = currentTime -currentTimeInt;
	if(currentTimePassed >beginTime)
	{
	//底部左边界和右边界
	float xBottomLeftBound;
	float xBottomRightBound;

	//此点边界
	float xPointLeftBound;
	float xPointRightBound;
	
	float x0 = currentTimePassed-beginTime;
	x0 /= loopTime;

	//设置右边界
	xBottomRightBound = x0;
	
	//设置左边界
	xBottomLeftBound = x0 - xLength;
	
	//投影至x的长度 = y/ tan(angle)
	float xProjL;
	xProjL= (uv.y)/tan(angleInRad);

	//此点的左边界 = 底部左边界 - 投影至x的长度
	xPointLeftBound = xBottomLeftBound - xProjL;
	//此点的右边界 = 底部右边界 - 投影至x的长度
	xPointRightBound = xBottomRightBound - xProjL;
	
	//边界加上一个偏移
	xPointLeftBound += offX;
	xPointRightBound += offX;
	
	//如果该点在区域内
	if(uv.x > xPointLeftBound && uv.x < xPointRightBound)
	{
		//得到发光区域的中心点
		float midness = (xPointLeftBound + xPointRightBound)/2.0;
		
		//趋近中心点的程度，0表示位于边缘，1表示位于中心点
		float rate= (xLength -2.0*abs(uv.x - midness))/ (xLength);
		brightness = rate;
	}
	}
	brightness= max(brightness,0.0);

	//返回颜色 = 纯白色 * 亮度
	//float4 col = vec4(1,1,1,1) *brightness;
	return brightness;
}

void main(void) {
	vec2 uvs = vTextureCoord.xy;
	vec4 fg = texture2D(uSampler, vTextureCoord);
	float t = iTime * 2.0;
	if (fg.a > 0.1){
		//fg.rgb += sin(customUniform + uvs.x * 2. + uvs.y * 2.) * 0.2;

		//float inFlash(float currentTime, float angle,vec2 uv,float xLength,float interval,float beginTime, float offX, float loopTime )
		fg.rgb += inFlash(t,75.0,uvs,0.25,10.0,2.0,0.15,2.7);
		gl_FragColor = fg * vColor;
	}
	else {
		gl_FragColor = fg;
	}
}
